﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using FluxJpeg.Core;
using System.IO;
using FluxJpeg.Core.Encoder;

namespace SUMO.MediaBrowser.Foundation
{
    public static class ImageManipulation
    {
        public static byte[] GetBase64Jpg(WriteableBitmap bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;
            int bands = 3;
            var raster = new byte[bands][,];

            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];
            }

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int pixel = bitmap.Pixels[width * row + column];
                    raster[0][column, row] = (byte)(pixel >> 16);
                    raster[1][column, row] = (byte)(pixel >> 8);
                    raster[2][column, row] = (byte)pixel;
                }
            }

            var model = new ColorModel { colorspace = ColorSpace.RGB };
            var img = new Image(model, raster);
            var stream = new MemoryStream();
            var encoder = new JpegEncoder(img, 90, stream);
            encoder.Encode();

            stream.Seek(0, SeekOrigin.Begin);
            var binaryData = new Byte[stream.Length];


            long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
            return binaryData;
        }
    }
}
